# -*- coding: utf-8 -*-

import requests
import logging
import json
from .client import Client
from .project import Project
from .repository import Repository


class DevCloud(object):
    def __init__(self, region=None, username=None, password=None, domain=None):
        if domain == None or domain == '':
            domain = username
        self.client = Client(region, username, password, domain)
        self.project_list = []
        self.repo_list = []

    def find_project_by_name(self, name):
        if self.project_list == []:
            self.projects()
        for prj in self.project_list:
            if prj.name == name:
                return prj
        return None
    
    def create_project_by_name(self, name):
        prj = Project.create(self.client, name)
        self.project_list.append(prj)
        return prj

    def projects(self):
        url = '/pcedge/v1/projects'
        #try:
        response = self.client.get_data(url)
        data = json.loads(response.text)['result']['projects']
        for item in data:
            self.project_list.append(Project(self.client, item))
        return self.project_list
        #except:
        #    logging.error("Has tried to access url %s, failed!", url)
    
    def repositories(self):
        url = self.client.get_full_url('codehub','/v2/projects/repositories')        
        response = self.client.get_data(url)
        
        data = json.loads(response.text)['result']['repositories']
        for item in data:
            self.repo_list.append(Repository(self.client, item))
        return self.repo_list